package com.example.closethreadgracefully.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/my")
public class MyController {

    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    {
        /*新建一个线程池*/
        threadPoolExecutor = new ThreadPoolExecutor(5, 10,
                5L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(100));

    }


    @GetMapping("/startANewThread")//经过测试 不行
    public String test() throws InterruptedException {
        MyRunnable myRunnable = new MyRunnable(58746, stringRedisTemplate);
        Thread thread = new Thread(myRunnable);
        threadPoolExecutor.submit(thread);
        return "success";
    }

    @GetMapping("/stopThread")
    public String stopThread() {
        //往 redis 里面放一个 需要停止的的线程id
        stringRedisTemplate.opsForSet().add("stopThread", "58746");
        return "success";
    }

}
